package com.truonghau.xmeasure.commons;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ParseException;
import android.util.Log;

import com.truonghau.model.SmsDTO;
import com.truonghau.smstoxls.R;

public class FileUtil {
	public static String getTextFromFileVerification(String fileName,
			Context context) {
		try {
			FileInputStream fIn = context.openFileInput(fileName);
			InputStreamReader isr = new InputStreamReader(fIn);
			/*
			 * Prepare a char-Array that will hold the chars we read back in.
			 */
			char[] inputBuffer = new char[32];
			isr.read(inputBuffer);
			return new String(inputBuffer);
		} catch (Exception e) {
			System.err.println(e.getStackTrace().toString());
			return Constants.ERROR_STRING;
		}
	}

	public static String getTextFromFile(String fileName, Context context) {
		try {
			StringBuilder text = new StringBuilder();
			File f = new File(fileName);
			if (f.exists()) {
				BufferedReader br = new BufferedReader(new FileReader(f));
				String line;

				while ((line = br.readLine()) != null) {
					text.append(line);
					text.append('\n');
				}
			}
			return new String(text);
		} catch (Exception e) {
			System.err.println(e.getStackTrace().toString());
			return Constants.ERROR_STRING;
		}
	}

	public static void alertbox(String title, String mymessage, Context context) {
		new AlertDialog.Builder(context)
		.setMessage(mymessage)
		.setTitle(title)
		.setCancelable(true)
		.setNeutralButton(android.R.string.ok,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,
					int whichButton) {
			}
		}).show();
	}

	private static String readTxt(Context context, int keyId) {
		InputStream inputStream = context.getResources().openRawResource(keyId);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		int i;
		try {
			i = inputStream.read();
			while (i != -1) {
				byteArrayOutputStream.write(i);
				i = inputStream.read();
			}
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return byteArrayOutputStream.toString();
	}
	//export point list to excel
	private static HSSFWorkbook appendWB(HSSFWorkbook resultWorkbook, SmsDTO obj, boolean isNew){
		if(resultWorkbook == null) resultWorkbook = new HSSFWorkbook();
		HSSFSheet sheet = resultWorkbook.getSheet("Sheet0");
		//sheet.setColumnWidth(1, 50);
		int rowNum = sheet.getLastRowNum();
		//get total row
		HSSFRow totalRow = sheet.getRow(rowNum);
		Double khuATotal = Double.parseDouble(totalRow.getCell(2).getStringCellValue());
		Double khuBTotal = Double.parseDouble(totalRow.getCell(3).getStringCellValue());
		Double khuCTotal = Double.parseDouble(totalRow.getCell(4).getStringCellValue());
		Double mTotal = khuATotal + khuBTotal + khuCTotal;
		HSSFRow row = null;
		khuATotal = khuATotal + obj.getKhuA();
		khuBTotal = khuBTotal + obj.getKhuB();
		khuCTotal = khuCTotal + obj.getKhuC();
		mTotal = khuATotal + khuBTotal + khuCTotal;

		if(isNew){
			row = sheet.getRow(rowNum);
		}else {
			row = sheet.getRow(rowNum-1);
			Double khuATotalOld = Double.parseDouble(row.getCell(2).getStringCellValue());
			Double khuBTotalOld = Double.parseDouble(row.getCell(3).getStringCellValue());
			Double khuCTotalOld = Double.parseDouble(row.getCell(4).getStringCellValue());
			khuATotal = khuATotal - khuATotalOld;
			khuBTotal = khuBTotal - khuBTotalOld;
			khuCTotal = khuCTotal - khuCTotalOld;
			mTotal = khuATotal + khuBTotal + khuCTotal;
		}
		setCellValue(row, 0, String.valueOf(rowNum));
		setCellValue(row, 1, obj.getSysdate());
		setCellValue(row, 2, String.valueOf(obj.getKhuA()));
		setCellValue(row, 3, String.valueOf(obj.getKhuB()));
		setCellValue(row, 4, String.valueOf(obj.getKhuC()));
		setCellValue(row, 5, String.valueOf(obj.getKhuA() + obj.getKhuB() + obj.getKhuC()));

		//last day of month
		sheet = createTotalRow(sheet, resultWorkbook, Math.round(khuATotal), Math.round(khuBTotal), Math.round(khuCTotal), Math.round(mTotal), isNew);
		return  resultWorkbook;

	}
	private static HSSFWorkbook initeWB(HSSFWorkbook resultWorkbook, List<String> listHeader){
		if(resultWorkbook == null) resultWorkbook = new HSSFWorkbook();
		HSSFSheet sheet = resultWorkbook.createSheet();
		sheet = createExcelHeader(sheet, resultWorkbook, listHeader);
		return  resultWorkbook;
	}
	private static HSSFSheet createExcelHeader(HSSFSheet sheet, HSSFWorkbook resultWorkbook, List<String> listHeader){
		HSSFRichTextString header = null;
		//row 0
		HSSFRow row0 = sheet.createRow(0);
		for (int i = 0; i < listHeader.size(); i++) {
			header = new HSSFRichTextString(listHeader.get(i));
			header.applyFont(HSSFFont.BOLDWEIGHT_BOLD);
			row0.createCell(i).setCellValue(header);
		}
		//row total
		sheet = createTotalRow(sheet, resultWorkbook, 0, 0, 0, 0, true);
		return sheet;
	}
	private static HSSFSheet createTotalRow(HSSFSheet sheet, HSSFWorkbook resultWorkbook, long khuA, long khuB, long khuC, long total, boolean isNew){
		HSSFRichTextString header = null;
		int rowNum = sheet.getLastRowNum();
		HSSFRow row0 = null;
		if(!isNew){
			rowNum--;
			row0 = sheet.getRow(rowNum+1);
		}else {
			row0 = sheet.createRow(rowNum+1);
		}

		header = new HSSFRichTextString(String.valueOf(khuA));
		header.applyFont(HSSFFont.BOLDWEIGHT_BOLD);
		row0.createCell(2).setCellValue(header);

		header = new HSSFRichTextString(String.valueOf(khuB));
		header.applyFont(HSSFFont.BOLDWEIGHT_BOLD);
		row0.createCell(3).setCellValue(header);

		header = new HSSFRichTextString(String.valueOf(khuC));
		header.applyFont(HSSFFont.BOLDWEIGHT_BOLD);
		row0.createCell(4).setCellValue(header);

		header = new HSSFRichTextString(String.valueOf(total));
		header.applyFont(HSSFFont.BOLDWEIGHT_BOLD);
		row0.createCell(5).setCellValue(header);

		//row total

		return sheet;
	}
	private static void setCellValue(HSSFRow row, int colNum, String value) {
		if (value != null) {
			row.createCell(colNum).setCellValue(new HSSFRichTextString(value));
		}
	}
	public static String createFileXLS(String fileName, List<String> listHeader, Context context ) throws IOException{
		FileOutputStream fos = null;
		File file = new File(fileName);
		HSSFWorkbook wb=null;
		wb = initeWB(wb, listHeader);
		try {
			fos = new FileOutputStream(file);
			wb.write(fos);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return fileName;
	}
	public static String appendLineXLS(String fileName, SmsDTO sms, boolean isNewDate){
		FileOutputStream fos = null;
		File file = new File(fileName);
		HSSFWorkbook wb;
		try {
			wb = new HSSFWorkbook(new FileInputStream(fileName));
			wb = appendWB(wb, sms, isNewDate);
			fos = new FileOutputStream(file);
			wb.write(fos);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			Log.e(fileName, e1.getMessage());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			Log.e(fileName, e1.getMessage());
		}finally {
			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return fileName;
	}

}
